// ==UserScript==
// @name         百度记录
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://www.baidu.com/*
// @icon         https://www.google.com/s2/favicons?domain=baidu.com
// @grant        GM_xmlhttpRequest
// ==/UserScript==

(function () {
    'use strict'
    let appendToHead = (url) => {
        return new Promise(s => {
            let js1 = document.createElement('script');
            js1.src = url;
            document.head.append(js1);
            js1.onload = s;
        });
    };
    appendToHead('https://www.sunibas.cn/pages/KS/bmob.js')
        .then(() => {
            appendToHead('https://www.sunibas.cn/pages/KS/record.js')
                .then(() => {
                    over();
                })
        });
    let record = {};
    function over() {
        Bmob.initialize('693f7e27f97550ba','IBAS12');
        Bmob.User.login('ibas','ibas').then(console.log);
        record = new Record();
    }
    let request = {
        saveQuestion(li) {
            return record.add(li.text,li.answer)
                .then(ret => {
                    return {
                        data: {
                            id: ret.objectId,
                            text: li.text,
                            answer: li.answer
                        }
                    };
                });
            // return Promise.resolve(undefined);
        },
        getAnswer(id) {
            return record.getByObjectId(id)
                .then(ret => {
                    return {
                        data: {
                            id: id,
                            text: ret.question,
                            answer: ret.answer,
                        }
                    }
                });
        }
    };
    // 缓存搜索记录
    let cache = new (class {
        constructor() {
            this.rnd = `塃郒峂EH窷UM_SRECRH塃鸷H窷UM_FILE)M0H塃A赴?塃??f塃??圗??塃??圗<??)E?艵?)E@塃H??圗LH窶AJOR_F H塃PH窶INOR_FH塃H窶AJOR_TH塃pH窶INOR_TH墔€艵婱訢嬌?婾序e?)E??)M?)E?E蛤Y臘3?)M墔????^菈E鳫窼_LATH塃窷_LATH塃0岮?E(fn荔胬?Y尿XE蛤Y膨^球]繦峂囹U癏窫_LONGH塃@A赴岯?Y搴D墠?fn萀嬑?嫔H竁_LONGH塃PH窵AT_INC H塃H窵ONG_INCH塃pH窯S_COUNTH墔€?E8?Y蓑Y蒡^珧X黍YP?^唑YD?Y镇eh?Y万昨^向UX?H?]x?塃郒峂EH窷UM_SRECRH塃鸷H窷UM_FILE)M0H塃A赴?塃??f塃??圗??塃??圗<??)E?艵?)E@塃H??圗LH窶AJOR_F H塃PH窶INOR_FH塃H窶AJOR_TH塃pH窶INOR_TH墔€艵婱訢嬌?婾序e?)E??)M?)E?E蛤Y臘3?)M墔????^菈E鳫窼_LATH塃窷_LATH塃0岮?E(fn荔胬?Y尿XE蛤Y膨^球]繦峂囹U癏窫_LONGH塃@A赴岯?Y搴D墠?fn萀嬑?嫔H竁_LONGH塃PH窵AT_INC H塃H窵ONG_INCH塃pH窯S_COUNTH墔€?E8?Y蓑Y蒡^珧X黍YP?^唑YD?Y镇eh?Y万昨^向UX?H?]x?`;
            this.questions = [];
            this.top = null;
            this.start = parseInt(Math.random() * 20);
            this.init();
        }
        init() {
            this.top = document.getElementsByClassName('toplist1-tr_4kE4D')[0].parentElement;
            this.top.innerHTML = '';
            this._getAllCache();
        }
        // li = { text: '', answer: '', id: '' }
        _createOneLi(li) {
            this.questions.push(li);
            let dom = document.createElement('div');
            dom.classList.add('toplist1-tr_4kE4D');
            dom.innerHTML = `
                <div class="toplist1-td_3zMd4 opr-toplist1-link_2YUtD"><span
                    class="toplist1-hot_2RbQT c-index-single toplist1-hot-top_3xY_F undefined c-index-single-hot1 "
                    style="opacity:1;cursor: pointer;">X</span>
                    <span target="_blank" title="${li.text}" href="#" class="c-font-medium c-color-t opr-toplist1-subtitle_3FULy">${this.rnd.substring(this.start,this.start + 20)}</span>
                    <span class="c-text c-text-hot opr-toplist1-label_3Mevn get-answer" tar="${li.id}" style="cursor: pointer;background-color:${li.answer ? '#FF455B' : '#F60'};">G</span><!--9-->
                </div>
                <div class="toplist1-right-num_3FteC toplist1-td_3zMd4 answer_${li.id}" tar="${li.id}"
                     style="line-height:20px;position:relative;top:2px;" title="${li.answer}">${this.rnd.substring(this.start + 2,this.start + 4)}
                </div>`;
            let $this = this;
            dom.getElementsByClassName('get-answer')[0].onclick = function () {
                let id = this.getAttribute('tar');
                request.getAnswer(id).then(_ => _.data)
                    .then(li => {
                        $this._updateCache(li);
                        let answerDiv = document.getElementsByClassName(`answer_${id}`)[0];
                        if (li.content2) {
                            answerDiv.title = li.content2;
                            this.style.backgroundColor = "#FF455B";
                        } else {
                            if (li.answer) {
                                this.style.backgroundColor = "#FF455B";
                            }
                            answerDiv.title = li.answer;
                        }
                    });
            };
            this.top.append(dom);
            this.start += parseInt(Math.random() * 20);
            if (this.start > this.rnd.length - 30) {
                this.start = parseInt(Math.random() * 20);
            }
        }
        _getKeyMap() {
            let keyMaps = sessionStorage.getItem('_baidu_km_');
            if (!keyMaps) {
                keyMaps = [];
            } else {
                keyMaps = JSON.parse(keyMaps);
            }
            return keyMaps;
        }
        _updateCache(li) {
            // 将所有问题以字典保存
            let keyMaps = this._getKeyMap();
            if (li.content1) {
                li.text = li.content1;
            }
            if (li.content2) {
                li.answer = li.content2;
            }
            if (keyMaps.includes(li.id)) {
                sessionStorage.setItem(li.id,JSON.stringify(li));
            } else {
                sessionStorage.setItem(li.id,JSON.stringify(li));
                keyMaps.push(li.id);
                sessionStorage.setItem(`_baidu_km_`,JSON.stringify(keyMaps));
            }
        }
        _addToCache(li) {
            // 将所有问题以字典保存
            let keyMaps = this._getKeyMap();
            keyMaps.push(li.id);
            sessionStorage.setItem(li.id,JSON.stringify(li));
            sessionStorage.setItem(`_baidu_km_`,JSON.stringify(keyMaps));
        }
        _getAllCache() {
            let keyMaps = this._getKeyMap();
            keyMaps.forEach(k => {
                let v = sessionStorage.getItem(k);
                if (v) {
                    this._createOneLi(JSON.parse(v));
                }
            })
        }
        addQuestion(li) {
            // li.id = `id_${parseInt(Math.random() * 1000)}_${new Date().getTime()}`;
            return request.saveQuestion(li).then(_ => _.data).then(_li => {
                li.id = _li.id;
                this._addToCache(li);
                this._createOneLi(li);
                return "ok";
            });
        }
    });
    let submitBtn = document.getElementById('su');
    submitBtn.onclick = function(e) {
        e.preventDefault();
        cache.addQuestion({
            text: document.getElementById('kw').value,
            answer: '',
        }).then(() => {
            document.getElementById('form').submit();
        });
    }
})();

/*
(function() {
    'use strict';
    let request = {
        toParamString(obj) {
            return Object.keys(obj).map((key) => {
                return encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])
            }).join('&');
        },
        post(url,data) {
            return new Promise(s => {
                GM_xmlhttpRequest({
                    method: 'POST',
                    url: url,
                    //dataType: "json",
                    // data: 'words=btc:test&index=0',
                    data: request.toParamString(data),
                    onload: function(response) {
                        // console.log(response.responseText);
                        s(JSON.parse(response.responseText));
                    },
                    headers: { "Content-Type": "application/x-www-form-urlencoded" },
                });
            })
        },
        saveQuestion(li) {
            return request.post(`http://139.199.205.55:39000/recording/add`,{
                // id: li.id,
                label: 'baidu',
                content1: li.text
            });
        },
        getAnswer(id) {
            return request.post(`http://139.199.205.55:39000/recording/detail`,{
                id: id
            });
        }
    };
    // 缓存搜索记录
    let cache = new (class {
        constructor() {
            this.rnd = `塃郒峂EH窷UM_SRECRH塃鸷H窷UM_FILE)M0H塃A赴?塃??f塃??圗??塃??圗<??)E?艵?)E@塃H??圗LH窶AJOR_F H塃PH窶INOR_FH塃H窶AJOR_TH塃pH窶INOR_TH墔€艵婱訢嬌?婾序e?)E??)M?)E?E蛤Y臘3?)M墔????^菈E鳫窼_LATH塃窷_LATH塃0岮?E(fn荔胬?Y尿XE蛤Y膨^球]繦峂囹U癏窫_LONGH塃@A赴岯?Y搴D墠?fn萀嬑?嫔H竁_LONGH塃PH窵AT_INC H塃H窵ONG_INCH塃pH窯S_COUNTH墔€?E8?Y蓑Y蒡^珧X黍YP?^唑YD?Y镇eh?Y万昨^向UX?H?]x?塃郒峂EH窷UM_SRECRH塃鸷H窷UM_FILE)M0H塃A赴?塃??f塃??圗??塃??圗<??)E?艵?)E@塃H??圗LH窶AJOR_F H塃PH窶INOR_FH塃H窶AJOR_TH塃pH窶INOR_TH墔€艵婱訢嬌?婾序e?)E??)M?)E?E蛤Y臘3?)M墔????^菈E鳫窼_LATH塃窷_LATH塃0岮?E(fn荔胬?Y尿XE蛤Y膨^球]繦峂囹U癏窫_LONGH塃@A赴岯?Y搴D墠?fn萀嬑?嫔H竁_LONGH塃PH窵AT_INC H塃H窵ONG_INCH塃pH窯S_COUNTH墔€?E8?Y蓑Y蒡^珧X黍YP?^唑YD?Y镇eh?Y万昨^向UX?H?]x?`;
            this.questions = [];
            this.top = null;
            this.start = parseInt(Math.random() * 20);
            this.init();
        }
        init() {
            this.top = document.getElementsByClassName('toplist1-tr_4kE4D')[0].parentElement;
            this.top.innerHTML = '';
            this._getAllCache();
        }
        // li = { text: '', answer: '', id: '' }
        _createOneLi(li) {
            this.questions.push(li);
            let dom = document.createElement('div');
            dom.classList.add('toplist1-tr_4kE4D');
            dom.innerHTML = `
                <div class="toplist1-td_3zMd4 opr-toplist1-link_2YUtD"><span
                    class="toplist1-hot_2RbQT c-index-single toplist1-hot-top_3xY_F undefined c-index-single-hot1 "
                    style="opacity:1;cursor: pointer;">X</span>
                    <span target="_blank" title="${li.text}" href="#" class="c-font-medium c-color-t opr-toplist1-subtitle_3FULy">${this.rnd.substring(this.start,this.start + 20)}</span>
                    <span class="c-text c-text-hot opr-toplist1-label_3Mevn get-answer" tar="${li.id}" style="cursor: pointer;">G</span><!--9-->
                </div>
                <div class="toplist1-right-num_3FteC toplist1-td_3zMd4 answer_${li.id}" tar="${li.id}"
                     style="line-height:20px;position:relative;top:2px;" title="${li.answer}">${this.rnd.substring(this.start + 2,this.start + 4)}
                </div>`;
            let $this = this;
            dom.getElementsByClassName('get-answer')[0].onclick = function () {
                let id = this.getAttribute('tar');
                request.getAnswer(id).then(_ => _.data)
                    .then(li => {
                        $this._updateCache(li);
                        let answerDiv = document.getElementsByClassName(`answer_${id}`)[0];
                        answerDiv.title = li.content2;
                    });
            };
            this.top.append(dom);
            this.start += parseInt(Math.random() * 20);
            if (this.start > this.rnd.length - 30) {
                this.start = parseInt(Math.random() * 20);
            }
        }
        _getKeyMap() {
            let keyMaps = sessionStorage.getItem('_baidu_km_');
            if (!keyMaps) {
                keyMaps = [];
            } else {
                keyMaps = JSON.parse(keyMaps);
            }
            return keyMaps;
        }
        _updateCache(li) {
            // 将所有问题以字典保存
            let keyMaps = this._getKeyMap();
            if (li.content1) {
                li.text = li.content1;
            }
            if (li.content2) {
                li.answer = li.content2;
            }
            if (keyMaps.includes(li.id)) {
                sessionStorage.setItem(li.id,JSON.stringify(li));
            } else {
                sessionStorage.setItem(li.id,JSON.stringify(li));
                keyMaps.push(li.id);
                sessionStorage.setItem(`_baidu_km_`,JSON.stringify(keyMaps));
            }
        }
        _addToCache(li) {
            // 将所有问题以字典保存
            let keyMaps = this._getKeyMap();
            keyMaps.push(li.id);
            sessionStorage.setItem(li.id,JSON.stringify(li));
            sessionStorage.setItem(`_baidu_km_`,JSON.stringify(keyMaps));
        }
        _getAllCache() {
            let keyMaps = this._getKeyMap();
            keyMaps.forEach(k => {
                let v = sessionStorage.getItem(k);
                if (v) {
                    this._createOneLi(JSON.parse(v));
                }
            })
        }
        addQuestion(li) {
            // li.id = `id_${parseInt(Math.random() * 1000)}_${new Date().getTime()}`;
            return request.saveQuestion(li).then(_ => _.data).then(_li => {
                li.id = _li.id;
                this._addToCache(li);
                this._createOneLi(li);
                return "ok";
            });
        }
    });
    // cache._createOneLi({text: 'hhaha',answer: 'A'})
    let submitBtn = document.getElementById('su');
    submitBtn.onclick = function(e) {
        e.preventDefault();
        cache.addQuestion({
            text: document.getElementById('kw').value,
            answer: '',
        }).then(() => {
            document.getElementById('form').submit();
        });
    }
    // Your code here...
})();
*/
